package com.zhs.gccs.view.taskMap;

import static com.blankj.utilcode.util.ViewUtils.runOnUiThread;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.zhs.gccs.R;
import com.zhs.gccs.view.BaseView;
import com.zhs.gccs.view.Compass;

public class CompassView extends BaseView   {


    private ImageView arrowView;
    private Compass compass;

    public CompassView(@NonNull Context context) {
        super(context);
    }

    public CompassView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CompassView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void init(Context context, AttributeSet attrs, int defStyleAttr) {
        this.context = context;
        View view = LayoutInflater.from(context).inflate(R.layout.compass_layout, this, true);
        arrowView = (ImageView) view.findViewById(R.id.main_image_hands);
        setupCompass();
    }

    private void setupCompass() {
        compass = new Compass(context);
        compass.setAzimuthFix(90);
        compass.setListener(new Compass.CompassListener() {
            @Override
            public void onNewAzimuth(float azimuth) {
                // UI updates only in UI thread
                // https://stackoverflow.com/q/11140285/444966
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adjustArrow(azimuth);
                    }
                });
            }
        });
    }
    private float currentAzimuth;
    private void adjustArrow(float azimuth) {
        Animation an = new RotateAnimation(-currentAzimuth, -azimuth,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        currentAzimuth = azimuth;
        an.setDuration(500);
        an.setRepeatCount(0);
        an.setFillAfter(true);
        arrowView.startAnimation(an);
    }


}
